package com.datn.utils.places;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.datn.utils.DistanceUtils;
import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


public class JsonPlace extends Activity
{

	private static final String TAG = JsonPlace.class.getName();
	private static final String MAP_API_URL = "http://maps.google.com/maps";
	private static final String EXPORT_TYPE = "json";
	private static final String UTF_8 = "utf-8";
	private static final int NUM_OF_PLACE = 10;



	private Context mContext;
	//private Place nearbyPlace = null;
	public JsonPlace(Context context) 
	{
		// TODO Auto-generated constructor stub
		this.mContext = context;
	}


	//---------------------------------------------------------------------------------	
	public ArrayList<Place> getListAdressByType(String place,GeoPoint GPS) throws Exception
	{
		if (place == null) {
			Log.e(TAG, "Place is null");
			throw new IllegalArgumentException();
		}

		ArrayList<Place> result = null;
		/* http://maps.google.com/maps?q=atm&sll=21.029505,105.850566&num=10&output=json */

		try {
			URL mapUri = new URL(MAP_API_URL +
					"?q=" + place + 
					"&sll=" 
					+ GPS.getLatitudeE6()/1E6 
					+ "," 
					+ GPS.getLongitudeE6()/1E6
					+  
					"&num=" + NUM_OF_PLACE +
					"&output=" + EXPORT_TYPE +"&hl="+"vi"+
					"&oe=" + UTF_8);
			String jsonResponse = getResponseFromUrl(mapUri);
			if (jsonResponse != null) 
			{
				if (jsonResponse.contains("while(1);")) 
				{
					jsonResponse = jsonResponse.replace("while(1);", "");
				}

				// Create new JsonObject
				JSONObject jsonObject = new JSONObject(jsonResponse);
				//String marker = jsonObject.getString("overlays");
				JSONObject jsonOverlay= jsonObject.getJSONObject("overlays");
				//marker = marker.replace("{\"markers\":", "");
				//marker = urlDecode(marker);
				JSONArray jsonMarker= jsonOverlay.getJSONArray("markers");

				// Extract json response to place
				result = jsonToListAddress(jsonMarker.toString(),GPS);
			} else 
			{
				Toast.makeText(mContext, "Không tìm thấy ", Toast.LENGTH_LONG).show();
			}
		} catch (MalformedURLException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	//------------------------------------------------
	private ArrayList<Place> jsonToListAddress(String str_places, GeoPoint GPS) 
	{
		try {
			ArrayList<Place> places = new ArrayList<Place>();
			JSONArray  jsonPlaces  = new JSONArray(str_places);
			for (int i = 0; i < jsonPlaces.length(); i ++) 
			{
				JSONObject jsonPlace = (JSONObject)jsonPlaces.get(i);	
				JSONObject jsonLatLng = new JSONObject(jsonPlace.getString("latlng"));
				Place place   = new Place();
				place.setAddressLine(jsonPlace.getString("laddr").replace("{", ""));
				place.setName(jsonPlace.getString("name"));
				place.setLatitude(jsonLatLng.getDouble("lat"));
				place.setLongtitude(jsonLatLng.getDouble("lng"));
				
				GeoPoint endLocation=new GeoPoint((int)(place.getLatitude()*1E6), (int)(place.getLongtitude()*1E6));
				place.setDistance(String.format("%.2f", DistanceUtils.calculateDistance(GPS, endLocation)) +" km");
				
				JSONObject jsonInfoWindow=new JSONObject();
				try {
					jsonInfoWindow = jsonPlace.getJSONObject("infoWindow");
				} catch (Exception e) {
					// TODO: handle exception
					place.setActualurl("");
					place.setPhonenumber("");
				}


				try {				
					JSONObject jsonHp=jsonInfoWindow.getJSONObject("hp");
					place.setActualurl(jsonHp.getString("actual_url"));				
				} catch (Exception e) {
					// TODO: handle exception
					place.setActualurl("");
				}

				try {
					JSONArray jsonPhone=jsonInfoWindow.getJSONArray("phones");
					JSONObject phone = (JSONObject) jsonPhone.get(0);
					place.setPhonenumber(phone.getString("number"));
				} catch (Exception e) {
					// TODO: handle exception
					place.setPhonenumber("");
				}


				places.add(place);
			}
			return places;
		} catch (JSONException e) 
		{
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	//-----------------------------------
	private static String getResponseFromUrl(URL url) 
	{
		try {
			URLConnection urlConnection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			StringBuilder strBuilder = new StringBuilder();
			String temp;
			while ((temp = in.readLine()) != null) {
				strBuilder.append(temp);
			}
			return strBuilder.toString();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} 
		return null;
	}
	//--------------------------------------
/*	private static String urlDecode(String target) 
	{
		try {
			return URLDecoder.decode(target, "utf-8");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
*/
}
